<!--
 * @Author: zy
 * @Date: 2022-06-09 16:24:45
 * @LastEditTime: 2022-07-26 18:52:23
 * @Description: 上传图片
-->
<template>
  <view>
    <u-upload :fileList="fileList" multiple @afterRead="afterRead" @delete="deletePic" name="xf-upload" :maxCount="4">
    </u-upload>
  </view>
</template>

<script>
  import {
    bucketSn
  } from '@/config'
  import {
    getFileExt,
    createPicKey
  } from '@/utils/index'

  export default {
    props: {},
    data() {
      return {
        fileList: []
      }
    },
    created() {

    },
    watch: {
      fileList: {
        handler(newValue, oldValue) {
          let fileUrls = [];
          for (let i = 0; i < newValue.length; i++) {
            let url = newValue[i].url;
            if (url.indexOf("http") == 0) {
              fileUrls.push(url)
            }
          }
          this.$emit("fileUrls", fileUrls.join(","))
        },
        deep: true
      }
    },
    methods: {
      // 删除图片
      deletePic(event) {
        this.fileList.splice(event.index, 1)
      },
      // 新增图片
      async afterRead(event) {
        console.log(event)
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        let lists = [].concat(event.file)
        let fileListLen = this.fileList.length
        lists.map((item) => {
          this.fileList.push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          let fileExt = getFileExt(lists[i].name ? lists[i].name : lists[i].url);
          const file_url = await this.$api.autoUploadQiniu(fileExt, 'uni/xcx/upload/' + createPicKey(),
            bucketSn, lists[i].url);
          let item = this.fileList[fileListLen];
          this.fileList.splice(fileListLen, 1,
            Object.assign(item, {
              status: 'success',
              message: '',
              url: file_url
            }))
          fileListLen++
        }
      }
    }
  }

</script>

<style scoped lang="scss">

</style>
